const express = require('express');
const cors = require('cors');
require('dotenv').config();

const app = express();
const PORT = 3002;

// 基础中间件
app.use(cors());
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true }));

// 添加请求日志中间件
app.use((req, res, next) => {
  console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
  next();
});

// 加载documents路由
console.log('正在加载documents路由...');
try {
  const documentsRouter = require('./routes/documents');
  console.log('Documents路由加载成功，路由数量:', documentsRouter.stack.length);
  
  app.use('/api/documents', documentsRouter);
  console.log('Documents路由已挂载到 /api/documents');
} catch (error) {
  console.error('Documents路由加载失败:', error);
}

// 404处理
app.use((req, res) => {
  console.log(`404: ${req.method} ${req.url}`);
  res.status(404).json({
    success: false,
    message: '接口不存在',
    path: req.path
  });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`调试服务器启动在端口 ${PORT}`);
  console.log('测试URL: http://localhost:3002/api/documents/convert-to-pdf/contract_20250910_42.docx');
});

// 10秒后自动退出
setTimeout(() => {
  console.log('调试完成，退出...');
  process.exit(0);
}, 10000);